import Router from '../router'
import { MD5 } from './md5'

import {
  Message,
  // eslint-disable-next-line no-unused-vars
  Loading
} from 'element-ui'
export default {
  MD5(val) {
    return MD5(val)
  },
  dealGetData(data) {
    let param = ''
    if (data) {
      param = '?'
      for (const key in data) {
        // eslint-disable-next-line eqeqeq
        if (data[key] || data[key] == 0) {
          param += key + '=' + data[key] + '&'
        }
      }
      param = param.substring(0, param.length - 1)
    }
    return param
  },
  tip(flag, msg, path) { // 提示消息：成功1，提醒0，报错-1;path路由跳转
    if (flag > -1) {
      Message({
        message: msg,
        center: true,
        // eslint-disable-next-line eqeqeq
        type: flag == 1 ? 'success' : 'warning',
        duration: '2000',
        onClose() {
          path ? Router.push({
            path: path
          }) : null
        }
      })
    } else {
      Message({
        message: msg,
        center: true,
        type: 'error',
        duration: '2000'
      })
    }
    // Message.error(msg);
  },
  validRule(rule, value) {
    let reg = null
    let txt = '格式不正确'
    switch (rule) {
      case 'tel': // 匹配手机号
        reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/g
        txt = '手机号不正确'
        break
      case 'fixTel': // 国内电话
        reg = /^(((0\d{3}[\-])?\d{7}|(0\d{3}[\-])?\d{8}|(0\d{2}[\-])?\d{7}|(0\d{2}[\-])?\d{8}))([\-]\d{2,4})?$/
        break
      case 'identity': // 匹配身份证
        reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
        break
      case 'num': // 匹配非负整数
        reg = /^\d*$/
        break
      case 'int':
        reg = /^\d+$/
        txt = '请输入数字'
        break
      case 'integer': // 匹配整数
        reg = /^-?\d+$/g
        break
      case 'floatNum': // 匹配浮点数
        reg = /^(-?\d+)(\.\d{1,2})?$/
        break
      case 'floatPositiveNum': // 匹配非负浮点数
        reg = /^(\d+)(\.\d{1,2})?$/
        break
      case 'name': // 姓名
        reg = /^[\u4E00-\u9FA5]{2,10}$/
        txt = '限制2~10位汉字'
        break
      case 'username': // 会员昵称
        reg = /^[\u4E00-\u9FA5A-Za-z0-9_]{2,10}$/
        txt = '限制2~10位汉字、英语、数字或下划线'
        break
      case 'nickname': // 名称，如活动名称
        reg = /^([\u4E00-\u9FA5A-Za-z0-9]|_(?!_)){2,20}$/ // 2~20位名称
        txt = '限制2~20位汉字、英语、数字或下划线'
        break
      case 'commonname':
        reg = /^[\u4E00-\u9FA5A-Za-z0-9]{1,6}$/ // 级别称呼有用到
        txt = '限制1~6位汉字、英语或数字'
        break
      case 'scale':
        reg = /^\d\.([1-9]{1,2}|[0-9][1-9])$|^[1-9]\d{0,1}(\.\d{1,2}){0,1}$|^100(\.0{1,2}){0,1}$/ // 大于0，小于100，并且保留两位数
        // reg1= /^\d\.([1-9]{1,2}|[0-9][1-9])$|^[1-9]\d{0,1}(\.\d{1,2}){0,1}$|^100(\.0{1,2}){0,1}$/;
        txt = '限制0~100之间,最多保留两位数'
        break
      case 'email':
        reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        txt = '邮箱不正确'
        break
      default:
        break
    }
    return {
      valid: reg.test(value),
      tip: txt
    }
  },
  // 必填项已有required为空提示，只需验证格式
  // 使用格式如：this.$util.validRequiredIpt(value, callback,"tel")
  validRequiredIpt(value, callback, rule) {
    let valid
    // eslint-disable-next-line eqeqeq
    if (!value && parseInt(value) != 0) { // 为空不管
      return
    } else {
      const validObj = this.validRule(rule, value)
      valid = validObj.valid
      if (!valid) {
        // this.log({
        //     rule: rule,
        //     valid: valid,
        //     tip: validObj.tip
        // })
        callback(new Error(validObj.tip))
      } else {
        callback()
      }
    }
  },
  // 传isNeed时必填，不传可以不填。此时字段没有required*标识
  // 使用格式如：this.$util.validIpt(value, callback,"tel",true)
  validIpt(value, callback, rule, isNeed) {
    let valid
    // eslint-disable-next-line eqeqeq
    if (!value && parseInt(value) != 0) { // 为空
      if (isNeed) {
        callback(new Error('不能为空'))
      } else {
        callback()
      }
    } else {
      const validObj = this.validRule(rule, value)
      valid = validObj.valid
      if (!valid) {
        // this.log({
        //     rule: rule,
        //     valid: valid,
        //     tip: validObj.tip
        // })
        callback(new Error(validObj.tip))
      } else {
        callback()
      }
    }
  },
  log(msg) {
    console.log('%c%s', 'color: red; font-size: 16px;', JSON.stringify(msg))
  },
  // 节流函数
  varthrottle(func, delay) {
    var startTime = Date.now()
    return function() {
      var currTime = Date.now()
      var self = this
      var args = this.arguments
      if (currTime - startTime >= delay) {
        func.apply(self, args)
        startTime = Date.now()
      }
    }
  },
  // 获取某月的天数
  getMonthDays(myMonth) {
    const now = new Date()
    var monthStartDate = new Date(now.getFullYear(), now.getMonth(), 1)
    var monthEndDate = new Date(now.getFullYear(), now.getMonth() + 1, 1)
    var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24)
    return days
  },
  formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  },
  // 将日期转换成周
  getYearWeek(date) {
    var now = this.formatTime(date, 'Y-M-D')
    var date1 = new Date(now)
    var date2 = new Date(date1.getFullYear(), 0, 1)
    var day1 = date.getDay()
    // eslint-disable-next-line eqeqeq
    if (day1 == 0) day1 = 7
    var day2 = date2.getDay()
    // eslint-disable-next-line eqeqeq
    if (day2 == 0) day2 = 7
    var d = Math.round((date1.getTime() - date2.getTime() + (day2 - day1) * (24 * 60 * 60 * 1000)) / 86400000)
    return date1.getFullYear() + '第' + (Math.ceil(d / 7) + 1) + '周'
  },
  // 格式化日期
  formatTime(date, format) {
    var formateArr = ['Y', 'M', 'D', 'h', 'm', 's']
    var returnArr = []
    returnArr.push(date.getFullYear())
    returnArr.push(this.formatNumber(date.getMonth() + 1))
    returnArr.push(this.formatNumber(date.getDate()))
    returnArr.push(this.formatNumber(date.getHours()))
    returnArr.push(this.formatNumber(date.getMinutes()))
    returnArr.push(this.formatNumber(date.getSeconds()))

    for (var i in returnArr) {
      format = format.replace(formateArr[i], returnArr[i])
    }
    return format
  },
  // 获取指定日期的前后n天
  getLastDate(date, days) {
    const newDate = new Date(date.getTime() + 24 * 3600 * 1000 * days)
    return newDate
  },
  // 自定义选择控件需要的数据（时间）
  getQuickDate(type) {
    const _this = this
    const now = new Date()
    var start = null
    var end = null
    switch (type) {
      case '1':// 今天
        start = new Date(new Date(now.toLocaleDateString()).getTime())
        end = new Date(new Date(now.toLocaleDateString()).getTime() + 24 * 3600 * 1000 - 1)
        return [start, end]
        // eslint-disable-next-line no-unreachable
        break
      case '2': // 昨天
        start = new Date(new Date(now.toLocaleDateString()).getTime() - 3600 * 1000 * 24)
        end = new Date(new Date(now.toLocaleDateString()).getTime() - 1)
        return [start, end]
        // eslint-disable-next-line no-unreachable
        break
      case '3': // 本周
        start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay())
        end = new Date(new Date(new Date(now.getFullYear(), now.getMonth(), now.getDate() + (7 - now.getDay() - 1)).toLocaleDateString()).getTime() + 24 * 3600 * 1000 - 1)
        return [start, end]
        // eslint-disable-next-line no-unreachable
        break
      case '4': // 上周
        start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay() - 7)
        end = new Date(new Date(new Date(now.getFullYear(), now.getMonth(), now.getDate() + (7 - now.getDay() - 1) - 7).toLocaleDateString()).getTime() + 24 * 3600 * 1000 - 1)
        return [start, end]
        // eslint-disable-next-line no-unreachable
        break
      case '5': // 本月
        start = new Date(now.getFullYear(), now.getMonth(), 1)
        end = new Date(new Date(new Date(now.getFullYear(), now.getMonth(), _this.getMonthDays(now.getMonth())).toLocaleDateString()).getTime() + 24 * 3600 * 1000 - 1)
        return [start, end]
        // eslint-disable-next-line no-unreachable
        break
      case '6': // 上月
        now.setDate(1)
        now.setMonth(now.getMonth() - 1)
        start = new Date(now.getFullYear(), now.getMonth(), 1)
        end = new Date(new Date(new Date(now.getFullYear(), now.getMonth(), _this.getMonthDays(now.getMonth())).toLocaleDateString()).getTime() + 24 * 3600 * 1000 - 1)
        return [start, end]
        // eslint-disable-next-line no-unreachable
        break
    }
  },
  // 日期时间选择器快捷选项
  setPickerOptions() {
    const _this = this
    return {
      shortcuts: [
        {
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', _this.getQuickDate('1'))
          }
        },
        {
          text: '昨天',
          onClick(picker) {
            picker.$emit('pick', _this.getQuickDate('2'))
          }
        },
        {
          text: '本周',
          onClick(picker) {
            picker.$emit('pick', _this.getQuickDate('3'))
          }
        },
        {
          text: '上周',
          onClick(picker) {
            picker.$emit('pick', _this.getQuickDate('4'))
          }
        },
        {
          text: '本月',
          onClick(picker) {
            picker.$emit('pick', _this.getQuickDate('5'))
          }
        },
        {
          text: '上月',
          onClick(picker) {
            picker.$emit('pick', _this.getQuickDate('5'))
          }
        },
        {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }
      ]
    }
  },
  // 日期选择器快捷选项
  setPickerDateOptions() {
    return {
      shortcuts: [{
        text: '最近一周',
        onClick(picker) {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          picker.$emit('pick', [start, end])
        }
      }, {
        text: '最近一个月',
        onClick(picker) {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
          picker.$emit('pick', [start, end])
        }
      }, {
        text: '最近三个月',
        onClick(picker) {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
          picker.$emit('pick', [start, end])
        }
      }]
    }
  },
  // 月份选择器快捷选项
  setPickerMonthOptions() {
    return {
      shortcuts: [{
        text: '本月',
        onClick(picker) {
          picker.$emit('pick', [new Date(), new Date()])
        }
      }, {
        text: '今年至今',
        onClick(picker) {
          const end = new Date()
          const start = new Date(new Date().getFullYear(), 0)
          picker.$emit('pick', [start, end])
        }
      }, {
        text: '最近六个月',
        onClick(picker) {
          const end = new Date()
          const start = new Date()
          start.setMonth(start.getMonth() - 6)
          picker.$emit('pick', [start, end])
        }
      }]
    }
  }
}
